package com.h3bpm.kumhosunny.knowledge.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Portal.webservices.BPMService;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.kumhosunny.common.H3Property;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import com.h3bpm.kumhosunny.knowledge.enums.Knowledge;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @author zhangpf
 * @date 2019/8/19
 * @description 研发知识平台控制器
 */
@Controller
@RequestMapping("/Portal/kumhosunny/knowledgeupdate")
public class KnowledegeUpdateProcessController extends ControllerBase {


    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerBase.class);

    /**
     * 知识新增流程
     */
    private final static String MATERIALTRAITBYUPDATE =  "materialTraitByUpdate";


    private BPMService bpmService = new BPMServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();


    /****
     * 功能描述: 知识修改流程点击修改后。 采用方式，取知识新增流程数据来自动发起 知识数据流程  ，知识数据流程不需要审批。来实现数据保存功能。
     *
     * @Param: [instanceId]
     * @Return: void
     * @Author: zhangpf
     * @Date: 2019/8/20 9:09
     */
    @RequestMapping(value = "/updateKnowledgeStart",  method = {RequestMethod.POST,RequestMethod.GET},produces = "text/html;charset=UTF-8")
    public String  updateKnowledgeStart(String instanceId){

        LOGGER.warn("=======修改知识数据发起流程==========Start========instanceId:" + instanceId);

        try {
            InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
            String updateInstanceId = updateKnowledgeByDeatil(instanceData);
            String sql = "select a.objectId from ot_workitem a where a.instanceId='"+updateInstanceId+"' and a.ActivityCode='Activity2' and a.Participant = '"+ getUserValidator().getUserID()+"' limit 1";
            Thread.sleep(2000);
            DataTable dataTable =SqlUtil.doQuery(sql);
            return "redirect:/Portal/WorkItemSheets.html?WorkItemID="+dataTable.getEntityRows().get(0).getString("objectId");
        } catch (Exception e) {
            LOGGER.error("未找到workitemid");
            e.printStackTrace();
        }
          return "redirect:/Portal/InstanceSheets.html?InstanceId="+null;
    }

    /****
     * 功能描述: 根据 知识-修改 流程 发起 知识数据流程。保存数据
     *
     * @Param: [instanceData]
     * @Return: void
     * @Author: zhangpf
     * @Date: 2019/8/20 11:36
     */
    private String updateKnowledgeByDeatil(InstanceData instanceData) throws Exception {

        HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
        List<DataItemParam> updateParams = new ArrayList<>();
        // 处理类型是短文本的数据项
        for (String key : valueTable.keySet()) {
            if (!H3Property.BASEDTO.contains(key) && valueTable.get(key) instanceof String) {
                updateParams.add(new DataItemParam(key,valueTable.get(key)));
            }
        }
        updateParams.add(new DataItemParam("knowledgeInstanceId",instanceData.getInstanceId()));
        // 处理子表
        BizObject[] detailTable = (BizObject[])valueTable.get(Knowledge.materialTrait.name());
        if ( null != detailTable) {
            List<HashMap<String,Object>> detailValueList = new ArrayList<>();
            for (BizObject detail : detailTable) {
                HashMap<String,Object> detailValue = new HashMap<>(2);
                HashMap<String, Object> detailValueTable = detail.getValueTable();
                detailValue.put(Knowledge.paramName.name(),detailValueTable.get(Knowledge.paramName.name()));
                detailValue.put(Knowledge.paramAttribute.name(),detailValueTable.get(Knowledge.paramAttribute.name()));
                detailValue.put(Knowledge.paramType.name(),detailValueTable.get(Knowledge.paramType.name()));
                detailValue.put(Knowledge.paramMax.name(),detailValueTable.get(Knowledge.paramMax.name()));
                detailValue.put(Knowledge.testCondition.name(),detailValueTable.get(Knowledge.testCondition.name()));
                detailValue.put(Knowledge.paramMin.name(),detailValueTable.get(Knowledge.paramMin.name()));


                detailValueList.add(detailValue);
            }
            updateParams.add(new DataItemParam(MATERIALTRAITBYUPDATE,detailValueList));
        }


        // 处理附件，附件赋值方式比较特殊，此处采用，先发起流程再上传附件。
        User user = (User)getEngine().getOrganization().GetUnit(getUserValidator().getUserID());
        LOGGER.info("====== 发起知识数据流程=========发起人:" + user.getName() );

        BPMServiceResult bpmServiceResult = bpmService.StartWorkflow(H3Property.SYSTEMCODE,H3Property.SECRET,"knowledgeUpdateProcess",user.getCode(),false,updateParams);
        if (bpmServiceResult.isSuccess()) {
            // 方便区分，将 知识-修改 流程 为 父流程， 知识数据流程为子流程
            String childInstanceId = bpmServiceResult.getInstanceId();
            InstanceData childnstanceData = new InstanceData(getEngine(),childInstanceId, User.AdministratorID);

            // 复制 附件 ，最后参数 是否重写。
            AppUtility.getEngine().getBizObjectManager().CopyAttachments(instanceData.getSchemaCode(),instanceData.getBizObject().getObjectID(),Knowledge.document.name(),
                    childnstanceData.getSchemaCode(),childnstanceData.getBizObject().getObjectID(),Knowledge.document.name(),true);
            return childInstanceId;
        }
      return null;
    }




    /****
     * 功能描述: 知识修改流程结束，修改知识平台数据
     *
     * @Param: [instanceId]
     * @Return: void
     * @Author: zhangpf
     * @Date: 2019/8/20 9:09
     */
    @RequestMapping(value = "/updateKnowledgeEnd",  method = {RequestMethod.POST,RequestMethod.GET},produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void updateKnowledgeEnd(String instanceId){

        LOGGER.warn("=======修改知识数据发起流程==========Start========instanceId:" + instanceId);

        try {
            InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);

            updateKnowledgeByDeatilEnd(instanceData);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /****
     * 功能描述: 根据 知识-修改 流程结束 知识数据流程。保存数据
     *
     * @Param: [instanceData]
     * @Return: void
     * @Author: zhangpf
     * @Date: 2019/8/20 11:36
     */
    private void updateKnowledgeByDeatilEnd(InstanceData instanceData) throws Exception {

        HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
        List<DataItemParam> updateParams = new ArrayList<>();

           String knowledgeInstanceId = valueTable.get("knowledgeInstanceId").toString();
          InstanceData knowledgeInstanceData = new InstanceData(getEngine(),knowledgeInstanceId, User.AdministratorID);

        // 处理类型是短文本的数据项
        for (String key : valueTable.keySet()) {
            if (!H3Property.BASEDTO.contains(key) && valueTable.get(key) instanceof String) {
                knowledgeInstanceData.getBizObject().setItem(key,valueTable.get(key));
            }
        }

        BizObject[] detailDataTable = (BizObject[]) instanceData.getBizObject().getValueTable().get(MATERIALTRAITBYUPDATE);
      if(detailDataTable!=null) {
          for (BizObject detail : detailDataTable) {
              String objectId = UUID.randomUUID().toString();
              detail.setObjectID(objectId);
              detail.setItem("ParentObjectID", knowledgeInstanceData.getBizObject().getObjectID());
              detail.setItem("ObjectID", objectId);
              detail.setItem("ParentPropertyName", Knowledge.materialTrait.name());
          }
      }
        knowledgeInstanceData.getBizObject().setItem(Knowledge.materialTrait.name(),detailDataTable);
        knowledgeInstanceData.Submit();

        AppUtility.getEngine().getBizObjectManager().RemoveAttachments(knowledgeInstanceData.getSchemaCode(),knowledgeInstanceData.getBizObject().getObjectID(),Knowledge.document.name()) ;
        //复制 附件 ，最后参数 是否重写。
        AppUtility.getEngine().getBizObjectManager().CopyAttachments(instanceData.getSchemaCode(),instanceData.getBizObject().getObjectID(),Knowledge.document.name(),
                knowledgeInstanceData.getSchemaCode(),knowledgeInstanceData.getBizObject().getObjectID(),Knowledge.document.name(),true);

    }








    @Override
    public String getFunctionCode() {
        return null;
    }
}
